import java.util.Scanner;

/**
 * @author yu
 * @date 2025年05月20日 23:31
 * 深搜 求岛屿数量
 */
public class _10_gird_02_kama99_dfs {
    public static int[][] dir = {{0,1},{1,0},{-1,0},{0,-1}};

    public static void dfs(boolean[][] visited,int x,int y,int[][] grid){
        for (int i = 0; i < 4; i++) {
            int nextX = x+dir[i][0];
            int nextY = y+dir[i][1];
            if(nextY < 0 || nextX < 0 || nextX >= grid.length || nextY >= grid.length)
                continue;
            if(!visited[nextX][nextY] && grid[nextX][nextY] == 1){
                visited[nextX][nextY] = true;
                dfs(visited,nextX,nextY,grid);
            }
        }
    }

    public static void main(String[] args) {
        try(Scanner sc = new Scanner(System.in)){
            System.out.println("请输入长宽 m n :");
            int m = sc.nextInt();
            int n = sc.nextInt();

            int[][] grid = new int[m][n];
            System.out.println("请逐行输入 0 和 1");
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    grid[i][j] = sc.nextInt();
                }
            }

            boolean[][] visited = new boolean[m][n];
            int res = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if(!visited[i][j] && grid[i][j] == 1){
                        res++;
                        visited[i][j] = true;
                        dfs(visited,i,j,grid);
                    }
                }
            }

            System.out.println("\n岛屿数量：" + res);
        }catch (Exception e){
            System.out.println("异常");
        }
    }
}
